//
//  HMRefreshControl.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/9/26.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit

//下拉刷新控件的状态
enum HMRefreshControlState {
    //下拉刷新
    case normal
    //释放刷新
    case pulling
    //正在刷新
    case refreshing
}

class HMRefreshControl: UIControl {

    //记录当前滚动视图
    var currentScrollView:UIScrollView?
    
    //当前状态
    var HMState:HMRefreshControlState = .normal {
        didSet {
            switch HMState {
            case .normal:
                print("normal")
                //如果是下拉刷新，箭头重置，停止风火轮，文字信息显示下拉刷新
                iconImageView.isHidden = false
                indicatorView.stopAnimating()
                UIView.animate(withDuration: 0.25, animations: { 
                    self.iconImageView.transform = CGAffineTransform.identity
                })
                //判断上一个状态如果是正在刷新就回归原位,方法：减去自身高度
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.currentScrollView?.contentInset.top -= 50
                    })
                }
                messageLabel.text = "下拉刷新"
            case .pulling:
                print("pulling")
                //如果是释放刷新，箭头不隐藏，箭头向上，文字信息显示释放刷新
                UIView.animate(withDuration: 0.25, animations: { 
                    self.iconImageView.transform = CGAffineTransform(rotationAngle:CGFloat(M_PI))
                })
                messageLabel.text = "释放刷新"
            case .refreshing:
                print("refreshing")
                //如果是正在刷新，隐藏箭头，开启风火轮，文字信息显示正在刷新
                iconImageView.isHidden = true
                indicatorView.startAnimating()
                messageLabel.text = "正在刷新"
                //设置停留,方法：加自身高度
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.currentScrollView?.contentInset.top += 50
                })
                //发送数据请求
                sendActions(for: .valueChanged)
            
            }
        }
    }
    
    //结束刷新的方法
    func endRefreshing() -> Void {
        //结束刷新后恢复下拉刷新状态
        HMState = .normal
    }
    //懒加载控件
    //箭头
    private lazy var iconImageView:UIImageView = UIImageView(image:UIImage(named:"tableview_pull_refresh"))
    //风火轮
    private lazy var indicatorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.gray)
    //文字信息
    private lazy var messageLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = UIColor.gray
        label.textAlignment = .center
        label.text = "下拉刷新"
        return label
        
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
//        self.frame.size = CGSize(width:ScreenWidth,height:50)
//        self.frame.origin.y = -50
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setUpUI() {
        backgroundColor = UIColor.red
        addSubview(iconImageView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        //控件布局
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: iconImageView, attribute: .centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .left, relatedBy: .equal, toItem: iconImageView, attribute: .right, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
    }
    
    //获取父控件
    override func willMove(toSuperview newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
        //执行到此说明父视图可以滚动
        self.frame.size = CGSize(width:scrollView.frame.size.width,height:50)
        self.frame.origin.y = -50
        //使用kvo监听偏移量
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        //记录当前的滚动视图
        currentScrollView = scrollView
    }
    
    //偏移量发生变化会调用的方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print(currentScrollView?.contentOffset.y)
        
        let contentOffsetY = currentScrollView!.contentOffset.y
        //临界点
        let maxY = -(currentScrollView!.contentInset.top + 50)
        //判断状态
        if currentScrollView!.isDragging {
            //拖动情况下只有两种状态
            //如果偏移量小于临界点且状态是下拉刷新，就让状态改为释放刷新
            if contentOffsetY < maxY && HMState == .normal {
                print("释放刷新")
                HMState = .pulling
                //如果偏移量大于临界点且状态为释放刷新，就让状态改为下拉刷新
            }else if contentOffsetY > maxY && HMState == .pulling {
                print("下拉刷新")
                HMState = .normal
            }
        }else {
            //此处为没有拖动的状态，且状态是释放刷新，就让状态改为正在刷新
            if HMState == .pulling {
                print("正在刷新")
                HMState = .refreshing
            }
            
        }
        
        
    
    
    }
    
    //移除kvo
    deinit {
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
